package com.dream.mqpushserver.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

@Component
public class ZKserver implements Watcher, SmartLifecycle {

    private CountDownLatch countDownLatch = new CountDownLatch(1) ;


    private static final String address = "120.27.243.49:2181" ;

    private ZooKeeper zooKeeper = null ;


    public void createNode(String path, String data, int version) throws KeeperException, InterruptedException {

        String s = zooKeeper.create(path, data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
        System.out.println("create " + s);
    }

    public String createNode2(String parPath , String targetPath, String data , String version ) throws KeeperException, InterruptedException {

        Stat exists = zooKeeper.exists(parPath, false);
        if (exists == null ){
            throw new RuntimeException("zookeeper parPath 不存在：[ " + parPath + " ] " );
        }
        return zooKeeper.create(String.format("%s/%s",parPath,targetPath), data.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL    ) ;
    }

    public static void main(String[] args) throws KeeperException, InterruptedException {
        ZKserver zKserver = new ZKserver();
        zKserver.start();
        for (int i = 0; i < 10; i++) {
            zKserver.createNode("/song/20200607","this is my test " + i, 1);
        }
        System.out.println(zKserver.createNode2("/song/zookeeper","helloservice","version:1,class:com.dream.mqpush","1.0.0"));
        Thread.sleep(3 * 1000 );
    }

    /**
     * 监视器 回调
     *
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected){
            System.out.println("process watchEvent is Sync connected ... ");
            this.countDownLatch.countDown();
        }
    }

    @Override
    public void start() {
        if (zooKeeper == null ){
            try {
                // 初始化是异步
                zooKeeper = new ZooKeeper(address,5 * 1000 , this);
                this.countDownLatch.await();
                System.out.println("started zk server .... ");
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public boolean isRunning() {
        return false;
    }
}
